# -*- encoding:utf-8 -*-
# @time: 2023/3/19 11:39
# @author: Maxs_hu
from django.conf import settings
from django.shortcuts import redirect
from django.shortcuts import render
from django.utils.deprecation import MiddlewareMixin
from django.http import JsonResponse
from utils import response


class userInfo(object):
    def __init__(self, role, username, id):
        self.role = role
        self.username = username
        self.id = id
        self.id = id
        self.parent = None
        self.menu_list = []


class MyMiddleWare(MiddlewareMixin):
    def process_request(self, request):
        # 1. 设置白名单
        if request.path_info in settings.NB_WHITE_URL:
            return None  # 不需要验证

        # 2. 验证session. 如果未登录跳转到登录界面
        user_info = request.session.get('user_info')
        if not user_info:
            return redirect('/login.html')

        # 3. 将user_info封装到request中(这个用处很大)
        request.user_obj = userInfo(**user_info)  # 使用**运算符将字典中的键-值对打散为函数的关键字参数
        # print(user_obj.username)
        # 这里可以添加通用信息到request中

        return None

    def process_view(self, request, callback, callback_args, callback_kwargs):
        # 不需要的登录就能访问的直接通过
        if request.path_info in settings.NB_WHITE_URL:
            return None

        # 0.让公共url的直接通过
        path_name = request.resolver_match.url_name  # 获取当前url对应的名字
        if path_name in settings.NB_PERMISSION_PUBLIC:
            return None

        # 1.根据用户角色获取url
        role = request.user_obj.role
        permission_info = settings.NB_PERMISSION[role]

        # 2.获取当前访问url的name

        # 3.判断是否具有权限访问. 判断是否为ajax请求. 如果没有权限则返回另外一种html
        if not path_name in permission_info:
            if request.is_ajax():
                resp = response.baseResponse()
                resp.status = False
                resp.detail = '无权访问'
                return JsonResponse(resp.dict, json_dumps_params={'ensure_ascii': False})
            return render(request, 'permission.html')

        # 4.有权限: 去找找他有没有父级
        menu_list = []  # 创建路径导航
        menu_list.append(permission_info[path_name]['text'])
        parent = path_name  # 设置初始值为当前url的name
        url_dic = permission_info[path_name]  # 需要做一次赋值. 因为后面需要修改
        while url_dic['parent']:  # 递归找父级. 直到父级不存在为止
            parent = url_dic['parent']
            url_dic = permission_info[parent]
            menu_list.append(url_dic['text'])  # 添加到menu列表中
        request.user_obj.parent = parent

        # 将路径反转为正序
        menu_list.append('首页')
        menu_list.reverse()
        request.user_obj.menu_list = menu_list
        return None

    def process_response(self, request, response):
        return response
